package com.hq.shop10search.service.impl;

import com.hq.commons.ov.Goods;
import com.hq.commons.utils.GsonUtils;
import com.hq.shop10search.service.GoodsService;
import com.hq.shop10search.vo.SearchGoodsParam;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {
    private String indexName = "2102-shop-goods-index";
    private String typeName = "2102-shop-goods-type";

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void addGoodsToEs(Goods goods) throws IOException {
        IndexRequest request = new IndexRequest(indexName, typeName);

        request.source(GsonUtils.toJSON(goods), XContentType.JSON);

        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexName);
    }

    @Override
    public List<Goods> seach(SearchGoodsParam searchGoodsParam) throws IOException {
        List<Goods> list = new ArrayList<>();
//        创建请求
        SearchRequest request = new SearchRequest();
//        设置索引和类型
        request.indices(indexName).types(typeName);
//        设置查询条件
        SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
//        开启关键字高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("gname");
        highlightBuilder.preTags(("<font color = 'red'>"));
        highlightBuilder.postTags("</font>");
        highlightBuilder.fragmentSize(50);
        sourceBuilder.highlighter(highlightBuilder);

//        添加排序规则
        if (searchGoodsParam.getOrderFile() != null) {

            switch (searchGoodsParam.getOrderFile()) {
                case 1:
                    sourceBuilder.sort("id", SortOrder.DESC);
                    break;
                case 2:
                    sourceBuilder.sort("gprice", SortOrder.DESC);
                    break;
                case 3:
                    sourceBuilder.sort("gtypePid", SortOrder.DESC);
                    break;
                case 4:
                    sourceBuilder.sort("gtypeCid", SortOrder.DESC);
                    break;
            }
        }
        request.source(sourceBuilder);
        if (!StringUtils.isEmpty(searchGoodsParam.getKeyWord())) {
//            按照关键字搜索
            request.source().query(QueryBuilders.multiMatchQuery(searchGoodsParam.getKeyWord(), "gname", "gdesc"));
        }
        if (searchGoodsParam.getType() != null) {
//            按照类型搜索
            request.source().query(QueryBuilders.termQuery("gtypeCid", searchGoodsParam.getType()));
        }
//        查询es
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
//        把JSON封装成Goods
        Goods goods = null;
        SearchHit[] hits = search.getHits().getHits();
        for (int i = 0; i < hits.length; i++) {
            SearchHit hit = hits[i];
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            goods = new Goods();
            try {
                BeanUtils.populate(goods, sourceAsMap);
//                判断当前数据是否高亮
                HighlightField gname = hit.getHighlightFields().get("gname");
                if (gname != null) {
                    String string = gname.getFragments()[0].toString();
                    goods.setGname(string);
                }
                list.add(goods);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        return list;
    }
}
